#!/bin/sh
#error and exit = set -e
#set -o errexit
#color
source /etc/init.d/functions
red='\033[0;31m'
green='\033[0;32m'
yellow='\033[0;33m'
plain='\033[0m'

function deal(){
  # Get the system name from /etc/os-release file
  SYSTEM=$(grep -oP '(?<=^NAME=").*(?=")' /etc/os-release)
  # Check the system name and print corresponding information
  case $SYSTEM in
    CentOS\ Linux)
      # If the system is CentOS Linux, print the system information using uname command
      mkdir -p /etc/yum.repos.d.bak
      mv /etc/yum.repos.d/* /etc/yum.repos.d.bak/ -f
      curl -sL https://mirrors.aliyun.com/repo/Centos-7.repo -o /etc/yum.repos.d/centos-aliyun-7.repo
      curl -sL https://mirrors.aliyun.com/repo/epel-7.repo -o /etc/yum.repos.d/epel-aliyun-7.repo
      # 非阿里云
      sed -i -e '/mirrors.cloud.aliyuncs.com/d' -e '/mirrors.aliyuncs.com/d' /etc/yum.repos.d/*aliyun*.repo
      ;;
    Rocky\ Linux)
      # If the system is Rocky Linux, print a simple message
      sed -e 's|^mirrorlist=|#mirrorlist=|g' \
          -e 's|^#baseurl=http://dl.rockylinux.org/$contentdir|baseurl=https://mirrors.aliyun.com/rockylinux|g' \
          -i.bak \
          /etc/yum.repos.d/Rocky-*.repo
      yum install -y https://mirrors.aliyun.com/epel/epel-release-latest-8.noarch.rpm > /dev/null 2>&1
      sed -i 's|^#baseurl=https://download.example/pub|baseurl=https://mirrors.aliyun.com|' /etc/yum.repos.d/epel*
      sed -i 's|^metalink|#metalink|' /etc/yum.repos.d/epel*
      ;;
    Anolis\ OS)
      # If the system is Anolis OS, print a simple message
      yum install -y https://mirrors.aliyun.com/epel/epel-release-latest-8.noarch.rpm > /dev/null
      sed -i 's|^#baseurl=https://download.example/pub|baseurl=https://mirrors.aliyun.com|' /etc/yum.repos.d/epel*
      sed -i 's|^metalink|#metalink|' /etc/yum.repos.d/epel*
      dnf clean all  > /dev/null
      dnf makecache  > /dev/null
	  
      ;;
    *)
      # If the system is neither CentOS nor Rocky, exit with an error message
      echo "Unsupported system: $SYSTEM"
      exit 1
  esac

}

function checkparam(){
  if [ $# -gt 0 ] ;then
    case $1 in
      "-f")
        return 1
        ;;
      "force")
        return 1
        ;;
      *)
        echo "vaild param is -f or force"
        exit -1
        ;;
    esac
  fi
}

function checkfile(){
  checkparam $*
  if [ $? -eq 1 ] ;then
    action "$0" deal
  else
    if [ -d /etc/yum.repos.d.bak ] ;then
      echo -e "${green}[$0] /etc/yum.repos.d.bak is exists. force update use param -f or force.${plain}"
      action "$0"
      return 0
    else
      action "$0" deal
    fi
  fi
}

function main(){
  checkfile $*
}

main $*
